<template>
  <div class="ppt-parser-test">
    <div class="test-header">
      <h1>🧪 PPT解析功能测试</h1>
      <p>上传PPT文件测试解析功能</p>
    </div>
    
    <div class="upload-section">
      <div class="upload-area" :class="{ 'dragover': isDragOver }" 
           @drop="handleDrop" 
           @dragover.prevent="isDragOver = true"
           @dragleave="isDragOver = false">
        <div class="upload-content">
          <div class="upload-icon">📄</div>
          <h3>拖拽PPT文件到这里</h3>
          <p>或者点击选择文件</p>
          <input 
            type="file" 
            ref="fileInput"
            @change="handleFileSelect"
            accept=".pptx,.ppt"
            style="display: none;"
          >
          <button @click="$refs.fileInput.click()" class="upload-btn">
            选择PPT文件
          </button>
        </div>
      </div>
      
      <!-- 解析进度 -->
      <div v-if="isProcessing" class="processing-status">
        <div class="spinner"></div>
        <p>{{ processingMessage }}</p>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progress + '%' }"></div>
        </div>
      </div>
    </div>
    
    <!-- 解析结果 -->
    <div v-if="parseResult" class="result-section">
      <div class="result-header">
        <h2>📊 解析结果</h2>
        <div class="result-stats">
          <div class="stat-item">
            <span class="stat-label">文件名:</span>
            <span class="stat-value">{{ fileName }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">解析状态:</span>
            <span class="stat-value" :class="parseResult.success ? 'success' : 'error'">
              {{ parseResult.success ? '✅ 成功' : '❌ 失败' }}
            </span>
          </div>
          <div class="stat-item" v-if="parseResult.success">
            <span class="stat-label">幻灯片数量:</span>
            <span class="stat-value">{{ parseResult.data.length }} 页</span>
          </div>
        </div>
        <p class="result-message">{{ parseResult.message }}</p>
      </div>
      
      <!-- 成功解析的内容 -->
      <div v-if="parseResult.success && parseResult.data" class="slides-preview">
        <h3>🎯 解析出的幻灯片内容</h3>
        
        <div class="slides-grid">
          <div 
            v-for="(slide, index) in parseResult.data" 
            :key="slide.id"
            class="slide-card"
            @click="selectSlide(index)"
            :class="{ 'active': selectedSlideIndex === index }"
          >
            <div class="slide-header">
              <span class="slide-number">{{ index + 1 }}</span>
              <span class="slide-type">{{ getSlideTypeIcon(slide.slideType) }}</span>
            </div>
            <div class="slide-title">{{ slide.title }}</div>
            <div class="slide-preview">
              <div class="slide-content-preview">
                {{ slide.script.substring(0, 100) }}{{ slide.script.length > 100 ? '...' : '' }}
              </div>
            </div>
            <div class="slide-meta">
              <span class="duration">⏱️ {{ slide.displayDuration }}s</span>
              <span class="type">{{ slide.slideType }}</span>
            </div>
          </div>
        </div>
        
        <!-- 详细信息面板 -->
        <div v-if="selectedSlide" class="slide-detail">
          <h3>📋 幻灯片详细信息</h3>
          <div class="detail-content">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>标题:</label>
                  <span>{{ selectedSlide.title }}</span>
                </div>
                <div class="detail-item">
                  <label>类型:</label>
                  <span>{{ selectedSlide.slideType }}</span>
                </div>
                <div class="detail-item">
                  <label>时长:</label>
                  <span>{{ selectedSlide.displayDuration }}秒</span>
                </div>
                <div class="detail-item">
                  <label>背景色:</label>
                  <span class="color-preview" :style="{ backgroundColor: selectedSlide.backgroundColor }">
                    {{ selectedSlide.backgroundColor }}
                  </span>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>文本内容</h4>
              <div class="text-content">
                {{ selectedSlide.script || '无文本内容' }}
              </div>
            </div>
            
            <div class="detail-section" v-if="selectedSlide.notes">
              <h4>备注</h4>
              <div class="notes-content">
                {{ selectedSlide.notes }}
              </div>
            </div>
            
            <div class="detail-section" v-if="selectedSlide.keywords">
              <h4>关键词</h4>
              <div class="keywords">
                <span v-for="keyword in selectedSlide.keywords.split(',')" 
                      :key="keyword" 
                      class="keyword-tag">
                  {{ keyword.trim() }}
                </span>
              </div>
            </div>
            
            <div class="detail-section" v-if="selectedSlide.pptImage">
              <h4>图片资源</h4>
              <div class="image-preview">
                <img :src="selectedSlide.pptImage" alt="幻灯片图片" />
              </div>
            </div>
            
            <div class="detail-section">
              <h4>原始数据 (调试用)</h4>
              <div class="raw-data">
                <pre>{{ JSON.stringify(selectedSlide.originalData, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button @click="exportToJSON" class="btn-export">
            📥 导出JSON数据
          </button>
          <button @click="testInViewer" class="btn-test">
            🎯 在查看器中测试
          </button>
          <button @click="saveToSystem" class="btn-save">
            💾 保存到系统
          </button>
        </div>
      </div>
      
      <!-- 解析失败的错误信息 -->
      <div v-else-if="!parseResult.success" class="error-details">
        <h3>❌ 解析失败详情</h3>
        <div class="error-content">
          <p><strong>错误信息:</strong> {{ parseResult.message }}</p>
          <div class="troubleshooting">
            <h4>🔧 故障排除建议:</h4>
            <ul>
              <li>确保文件是有效的 .pptx 或 .ppt 格式</li>
              <li>检查文件是否损坏或加密</li>
              <li>尝试用其他PPT软件重新保存文件</li>
              <li>确保文件大小不超过限制</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 调试信息 -->
    <div v-if="debugInfo" class="debug-section">
      <h3>🐛 调试信息</h3>
      <div class="debug-content">
        <pre>{{ debugInfo }}</pre>
      </div>
    </div>
  </div>
</template>

<script>
import pptParser from '@/utils/pptParser'

export default {
  name: 'PPTParserTest',
  data() {
    return {
      isDragOver: false,
      isProcessing: false,
      processingMessage: '',
      progress: 0,
      fileName: '',
      parseResult: null,
      selectedSlideIndex: -1,
      debugInfo: null
    }
  },
  computed: {
    selectedSlide() {
      if (this.selectedSlideIndex >= 0 && this.parseResult && this.parseResult.data) {
        return this.parseResult.data[this.selectedSlideIndex]
      }
      return null
    }
  },
  methods: {
    // 处理文件拖拽
    handleDrop(event) {
      event.preventDefault()
      this.isDragOver = false
      
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.processFile(files[0])
      }
    },
    
    // 处理文件选择
    handleFileSelect(event) {
      const files = event.target.files
      if (files.length > 0) {
        this.processFile(files[0])
      }
    },
    
    // 处理文件
    async processFile(file) {
      this.fileName = file.name
      this.parseResult = null
      this.selectedSlideIndex = -1
      this.debugInfo = null
      
      // 检查文件类型
      if (!pptParser.isSupportedFile(file)) {
        this.parseResult = {
          success: false,
          message: '不支持的文件类型，请选择 .pptx 或 .ppt 文件'
        }
        return
      }
      
      // 开始解析
      this.isProcessing = true
      this.progress = 0
      this.processingMessage = '正在读取文件...'
      
      try {
        // 模拟进度更新
        const progressInterval = setInterval(() => {
          if (this.progress < 90) {
            this.progress += Math.random() * 10
            if (this.progress < 30) {
              this.processingMessage = '正在读取文件...'
            } else if (this.progress < 60) {
              this.processingMessage = '正在解析PPT结构...'
            } else {
              this.processingMessage = '正在转换数据格式...'
            }
          }
        }, 200)
        
        // 执行解析
        const result = await pptParser.parsePPT(file)
        
        // 清除进度更新
        clearInterval(progressInterval)
        this.progress = 100
        this.processingMessage = '解析完成!'
        
        // 设置结果
        this.parseResult = result
        
        // 添加调试信息
        this.debugInfo = {
          fileName: file.name,
          fileSize: file.size,
          fileType: file.type,
          parseTime: new Date().toISOString(),
          result: result
        }
        
        setTimeout(() => {
          this.isProcessing = false
        }, 500)
        
      } catch (error) {
        console.error('解析过程出错:', error)
        this.parseResult = {
          success: false,
          message: `解析过程出错: ${error.message}`
        }
        this.isProcessing = false
      }
    },
    
    // 选择幻灯片
    selectSlide(index) {
      this.selectedSlideIndex = index
    },
    
    // 获取幻灯片类型图标
    getSlideTypeIcon(slideType) {
      const icons = {
        'title': '📝',
        'ppt': '📄',
        'image': '🖼️',
        'video': '🎬',
        'model': '🎯'
      }
      return icons[slideType] || '📄'
    },
    
    // 导出JSON数据
    exportToJSON() {
      if (!this.parseResult || !this.parseResult.success) return
      
      const dataStr = JSON.stringify(this.parseResult.data, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      
      const link = document.createElement('a')
      link.href = URL.createObjectURL(dataBlob)
      link.download = `${this.fileName.replace(/\.[^/.]+$/, '')}_parsed.json`
      link.click()
    },
    
    // 在查看器中测试
    testInViewer() {
      if (!this.parseResult || !this.parseResult.success) return
      
      // 临时保存数据到sessionStorage
      sessionStorage.setItem('testPPTData', JSON.stringify(this.parseResult.data))
      
      // 打开新窗口显示查看器
      const testUrl = `${window.location.origin}${window.location.pathname}#/ppt-viewer-test`
      window.open(testUrl, '_blank')
    },
    
    // 保存到系统
    async saveToSystem() {
      if (!this.parseResult || !this.parseResult.success) return
      
      try {
        // 动态导入数据管理器
        const { default: courseDataManager } = await import('@/utils/courseDataManager')
        
        // 创建新课程
        const courseId = `course-${Date.now()}`
        const courseData = {
          id: courseId,
          title: this.fileName.replace(/\.[^/.]+$/, ''),
          description: `从PPT文件 ${this.fileName} 解析生成的课程`,
          teacher: {
            name: '系统导入',
            avatar: 'static/img/teacher.png'
          },
          pptSlides: this.parseResult.data,
          status: 'draft',
          createdAt: new Date().toISOString()
        }
        
        // 保存课程
        courseDataManager.addCourse(courseData)
        
        alert(`课程已成功保存！\n课程ID: ${courseId}\n幻灯片数量: ${this.parseResult.data.length}`)
        
      } catch (error) {
        console.error('保存失败:', error)
        alert(`保存失败: ${error.message}`)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.ppt-parser-test {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #f8f9fa;
  min-height: 100vh;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    color: #2c3e50;
    margin-bottom: 10px;
  }
  
  p {
    color: #7f8c8d;
    font-size: 1.1rem;
  }
}

.upload-section {
  margin-bottom: 30px;
}

.upload-area {
  border: 3px dashed #bdc3c7;
  border-radius: 15px;
  padding: 40px;
  text-align: center;
  background: white;
  transition: all 0.3s ease;
  cursor: pointer;
  
  &:hover, &.dragover {
    border-color: #3498db;
    background: #f8f9ff;
    transform: translateY(-2px);
  }
  
  .upload-content {
    .upload-icon {
      font-size: 4rem;
      margin-bottom: 20px;
    }
    
    h3 {
      color: #2c3e50;
      margin-bottom: 10px;
    }
    
    p {
      color: #7f8c8d;
      margin-bottom: 20px;
    }
    
    .upload-btn {
      padding: 12px 24px;
      background: #3498db;
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 1rem;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: #2980b9;
        transform: translateY(-2px);
      }
    }
  }
}

.processing-status {
  text-align: center;
  padding: 30px;
  background: white;
  border-radius: 15px;
  margin-top: 20px;
  
  .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #ecf0f1;
    border-top-color: #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 20px;
  }
  
  p {
    color: #2c3e50;
    font-size: 1.1rem;
    margin-bottom: 20px;
  }
  
  .progress-bar {
    width: 100%;
    height: 8px;
    background: #ecf0f1;
    border-radius: 4px;
    overflow: hidden;
    
    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #3498db, #2ecc71);
      border-radius: 4px;
      transition: width 0.3s ease;
    }
  }
}

.result-section {
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.result-header {
  margin-bottom: 30px;
  
  h2 {
    color: #2c3e50;
    margin-bottom: 20px;
  }
  
  .result-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 15px;
    
    .stat-item {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .stat-label {
        font-weight: bold;
        color: #7f8c8d;
      }
      
      .stat-value {
        color: #2c3e50;
        
        &.success {
          color: #27ae60;
        }
        
        &.error {
          color: #e74c3c;
        }
      }
    }
  }
  
  .result-message {
    color: #7f8c8d;
    font-style: italic;
  }
}

.slides-preview {
  h3 {
    color: #2c3e50;
    margin-bottom: 20px;
  }
}

.slides-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.slide-card {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
  
  &.active {
    border-color: #3498db;
    background: #e8f4fd;
  }
  
  .slide-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    
    .slide-number {
      background: #3498db;
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 0.9rem;
      font-weight: bold;
    }
    
    .slide-type {
      font-size: 1.5rem;
    }
  }
  
  .slide-title {
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 10px;
    font-size: 1.1rem;
  }
  
  .slide-preview {
    .slide-content-preview {
      color: #7f8c8d;
      font-size: 0.9rem;
      line-height: 1.4;
      margin-bottom: 15px;
      min-height: 60px;
    }
  }
  
  .slide-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.8rem;
    color: #95a5a6;
    
    .duration {
      background: #ecf0f1;
      padding: 2px 6px;
      border-radius: 3px;
    }
    
    .type {
      text-transform: uppercase;
      font-weight: bold;
    }
  }
}

.slide-detail {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 25px;
  margin-bottom: 20px;
  
  h3 {
    color: #2c3e50;
    margin-bottom: 20px;
  }
  
  .detail-content {
    .detail-section {
      margin-bottom: 25px;
      
      h4 {
        color: #34495e;
        margin-bottom: 15px;
        font-size: 1.1rem;
      }
      
      .detail-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 15px;
        
        .detail-item {
          display: flex;
          align-items: center;
          gap: 10px;
          
          label {
            font-weight: bold;
            color: #7f8c8d;
            min-width: 80px;
          }
          
          .color-preview {
            padding: 4px 8px;
            border-radius: 4px;
            color: white;
            text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
          }
        }
      }
      
      .text-content, .notes-content {
        background: white;
        padding: 15px;
        border-radius: 8px;
        border-left: 4px solid #3498db;
        line-height: 1.6;
        color: #2c3e50;
      }
      
      .keywords {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .keyword-tag {
          background: #3498db;
          color: white;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 0.9rem;
        }
      }
      
      .image-preview {
        img {
          max-width: 100%;
          max-height: 300px;
          border-radius: 8px;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
      }
      
      .raw-data {
        background: #2c3e50;
        color: #ecf0f1;
        padding: 15px;
        border-radius: 8px;
        max-height: 300px;
        overflow-y: auto;
        font-family: 'Courier New', monospace;
        font-size: 0.8rem;
        
        pre {
          margin: 0;
          white-space: pre-wrap;
        }
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
  
  button {
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &.btn-export {
      background: #9b59b6;
      color: white;
      
      &:hover {
        background: #8e44ad;
      }
    }
    
    &.btn-test {
      background: #f39c12;
      color: white;
      
      &:hover {
        background: #e67e22;
      }
    }
    
    &.btn-save {
      background: #27ae60;
      color: white;
      
      &:hover {
        background: #229954;
      }
    }
  }
}

.error-details {
  background: #fdf2f2;
  border: 1px solid #f5c6cb;
  border-radius: 10px;
  padding: 25px;
  
  h3 {
    color: #721c24;
    margin-bottom: 15px;
  }
  
  .error-content {
    color: #721c24;
    
    .troubleshooting {
      margin-top: 20px;
      
      h4 {
        margin-bottom: 10px;
      }
      
      ul {
        padding-left: 20px;
        
        li {
          margin-bottom: 5px;
        }
      }
    }
  }
}

.debug-section {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 25px;
  margin-top: 30px;
  
  h3 {
    color: #2c3e50;
    margin-bottom: 15px;
  }
  
  .debug-content {
    background: #2c3e50;
    color: #ecf0f1;
    padding: 15px;
    border-radius: 8px;
    font-family: 'Courier New', monospace;
    font-size: 0.8rem;
    max-height: 400px;
    overflow-y: auto;
    
    pre {
      margin: 0;
      white-space: pre-wrap;
    }
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .ppt-parser-test {
    padding: 15px;
  }
  
  .slides-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
    
    button {
      width: 100%;
    }
  }
  
  .result-stats {
    grid-template-columns: 1fr;
  }
}
</style>
</code_block_to_apply_changes_from>
</rewritten_file>